<template>
  <div class="h-full px-4 pb-3 pt-4">
    <div class="flex justify-between">
      <div>
        <a-button class="ghost" @click="openModal('add')">
          添加巡视点位
        </a-button>
      </div>
      <div class="flex justify-end">
        <a-input
          class="_input"
          v-model:value.trim="searchForm.name"
          placeholder="请输入巡视点位名称"
          v-filter-special-chars
        />
        <a-input
          class="_input"
          v-model:value.trim="searchForm.deviceName"
          placeholder="请输入设备名称"
          v-filter-special-chars
        />
        <a-input
          class="_input"
          v-model:value.trim="searchForm.partName"
          placeholder="请输入部件名称"
          v-filter-special-chars
        />
        <SerchButtom @search="getList(true, true)" @reset="reset" />
      </div>
    </div>

    <div class="mt-3 h-[calc(100%-6rem)] overflow-y-auto">
      <a-table
        :dataSource="dataSource"
        :pagination="false"
        :columns="columns"
        :loading="loading"
      >
        <template #bodyCell="{ column, index, record }">
          <template v-if="column.dataIndex === 'order'">
            {{ (pagination.current - 1) * pagination.pageSize + index + 1 }}
          </template>
          <template v-else-if="column.dataIndex === 'isMultiplePatrol'">
            <a-checkbox
              v-model:checked="record.isMultiplePatrol"
              @change="($event: any) => handleCheckBox($event, record)"
            >
              关联多终端融合
            </a-checkbox>
          </template>
          <template v-else-if="column.dataIndex === 'angle'">
            <a-button type="link" @click="getAngleRef(record)">
              映射视场角
            </a-button>
          </template>
          <template v-else-if="column.dataIndex === 'operation'">
            <a-button
              type="link"
              class="delete"
              @click="openModal('delete', record)"
            >
              删除
            </a-button>
            <a-button type="link" @click="openModal('edit', record)">
              修改
            </a-button>
          </template>
        </template>
      </a-table>
    </div>

    <div class="mt-3 h-8">
      <Pagination @getListByPage="getListByPage" ref="paginationRef" />
    </div>
  </div>

  <IndexModal
    ref="indexModalRef"
    :selectList="deviceList"
    @isOk="getList(true, true)"
  />

  <TourModal
    ref="tourModalRef"
    :selectList="deviceList"
    @isOk="getList(true, true)"
  />

  <ThreeAngle
    ref="threeAngleRef"
    :data="threeAngleData"
    @confirm="submitAngle"
  />
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { message } from 'ant-design-vue'

import IndexModal from './IndexModal.vue'
import TourModal from './TourModal.vue'
import SerchButtom from '@/components/YuanQi-SearchButtom.vue'

import ThreeAngle from '../ThreeAngle.vue'

import { list, edit, device, editAngle } from './serve.api'

const dataSource = ref()
const loading = ref<boolean>(false)
const paginationRef = ref()
const deviceList = ref<any[]>([])

const threeAngleRef = ref()
const threeAngleData = reactive({
  id: 0
})

let searchFormClone = {
  pageNum: 1,
  pageSize: 10,
  name: '',
  deviceName: undefined,
  partName: undefined
}

// 搜索参数
const searchForm = reactive({
  name: '',
  deviceName: undefined,
  partName: undefined
})

const columns = ref([
  {
    title: '序号',
    dataIndex: 'order',
    width: '7.5rem'
  },
  {
    title: '巡视点位名称',
    dataIndex: 'name',
    key: 'name',
    ellipsis: true
  },
  {
    title: '设备名称',
    dataIndex: 'deviceName',
    key: 'deviceName',
    ellipsis: true
  },
  {
    title: '部件名称',
    dataIndex: 'partName',
    key: 'partName',
    ellipsis: true
  },
  {
    title: '关联多终端融合',
    dataIndex: 'isMultiplePatrol',
    key: 'isMultiplePatrol',
    ellipsis: true
  },
  {
    title: '巡视点位详情',
    dataIndex: 'angle',
    key: 'angle',
    ellipsis: true
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    ellipsis: true,
    width: '12rem'
  }
])

// 重置
const reset = () => {
  searchForm.name = ''
  searchForm.deviceName = undefined
  searchForm.partName = undefined
  getList(true, true)
}

const pagination = reactive({
  total: 0,
  pageSize: 10, // 每页中显示10条数据
  position: ['bottomCenter'],
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`
})

// 映射视场角
function getAngleRef(record: any) {
  if (record) {
    const cloneData = JSON.parse(JSON.stringify(record))
    threeAngleData.id = cloneData.id
    const threeDimensionalParam = JSON.parse(cloneData.threeDimensionalParam)
    nextTick(() => {
      threeAngleRef.value.showModal(threeDimensionalParam)
    })
  }
}

// 修改映射视场角
async function submitAngle(value: any) {
  try {
    await editAngle({
      id: threeAngleData.id,
      threeDimensionalParam: JSON.stringify(value)
    })
    getList(true, true)
    message.success('修改映射视场角成功')
  } catch {
    message.error('修改映射视场角失败')
  }
}

// 初始化数据
const getList = (flag = false, isSearch = false) => {
  if (flag) {
    pagination.current = 1
    paginationRef.value.changeCurrent(pagination.current)
  }
  loading.value = true
  dataSource.value = []

  const params = {
    name: searchForm.name,
    deviceName: searchForm.deviceName,
    partName: searchForm.partName,
    pageNum: pagination.current,
    pageSize: pagination.pageSize
  }
  if (isSearch) {
    searchFormClone = JSON.parse(JSON.stringify(params))
  } else {
    params.name = searchFormClone.name
    params.deviceName = searchFormClone.deviceName
    params.partName = searchFormClone.partName
  }

  list(params)
    .then((res) => {
      if (res) {
        console.log(res, '巡视点-摄像机列表')

        dataSource.value = res.list
        pagination.total = res.total

        paginationRef.value.changeTotal(pagination.total)
        loading.value = false
      } else {
        loading.value = false
      }
    })
    .catch(() => {
      loading.value = false
    })
}

const getListByPage = (page: number, pageSize: number) => {
  if (pagination.current !== page) {
    pagination.current = page
    getList()
  }
  if (pagination.pageSize !== pageSize) {
    pagination.pageSize = pageSize
    getList(true)
  }
}

// 新增/编辑/删除操作
type ModalType = 'add' | 'delete' | 'edit' | 'detail'
const indexModalRef = ref()
const tourModalRef = ref()

const openModal = (type: ModalType, data?: any) => {
  if (['add', 'edit'].includes(type))
    return tourModalRef.value.showModal(type, data)
  indexModalRef.value.showModal(type, data)
}

// 关联多终端融合
async function handleCheckBox(e: any, item: any) {
  const isPatrol = e.target.checked ? 1 : 0
  try {
    await edit({
      id: item.id,
      isMultiplePatrol: isPatrol
    })
    message.success(`${e.target.checked ? '成功' : '取消'}关联多终端融合`)
  } catch {
    item.isMultiplePatrol = !item.isMultiplePatrol
  }
  getList(true, true)
}

onMounted(() => {
  device().then((res) => {
    res.forEach((item: any) => {
      item.id = String(item.id)
    })
    deviceList.value = res
    console.log(res, '设备列表')
  })

  getList(true, true)
})
</script>
<style lang="less" scoped>
._input {
  width: 13.125rem;
  vertical-align: middle;

  &:not(:first-child) {
    margin-left: 1.25rem;
  }
}
</style>
